package codegen

import (
	"fmt"
	"gitee.com/hxchjm/goge/codegen/utils"
	"gitee.com/hxchjm/goge/codegen/utils/pathx"
	"github.com/siddontang/go/config"
	"strings"
)

const dbTemplate = `package dao

import (
	"go-main/library/conf"
	"go-main/library/database/sql"
)

func NewDB() (db *sql.DB, cf func(), err error) {
	var cfg sql.Config
	if err = conf.Bind("db", &cfg); err != nil {
		return
	}
	db = sql.NewMySQL(&cfg)
	cf = func() { _ = db.Close() }
	return
}
`

func genDB(dir, rootPkg string, cfg *config.Config, filename string) error {
	//name := strings.ToLower(api.Service.Name)
	//filename, err := format.FileNamingFormat(cfg.NamingFormat, name)
	//if err != nil {
	//	return err
	//}

	/*	filename := name
		configName := filename
		if strings.HasSuffix(filename, "-api") {
			filename = strings.ReplaceAll(filename, "-api", "")
		}*/

	return utils.GenFile(utils.FileGenConfig{
		Dir:          dir,
		Subdir:       daoDir,
		Filename:     filename,
		TemplateName: "mainTemplate",
		//Category:        category,
		//TemplateFile:    mainTemplateFile,
		BuiltinTemplate: dbTemplate,
		Data: map[string]string{
			"importPackages": genDBImports(rootPkg),
			"serviceName":    rootPkg,
		},
	})
}

func genDBImports(parentPkg string) string {
	var imports []string
	imports = append(imports, fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, appDir)))
	//imports = append(imports, fmt.Sprintf("\"%s/core/conf\"", vars.ProjectOpenSourceURL))
	//imports = append(imports, fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceURL))
	return strings.Join(imports, "\n\t")
}
